package com.hoolai.qps.server.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import redis.clients.jedis.BinaryJedis;

import com.google.protobuf.InvalidProtocolBufferException;
import com.hoolai.qps.bo.Player;
import com.hoolai.qps.proto.RespCmdProto.NotifyCodeProto;
import com.hoolai.qps.proto.RespCmdProto.UserProto;
import com.hoolai.qps.server.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private BinaryJedis jedis;

    @Override
    public void getUser(Player player) {
        byte[] bytes = jedis.get(("u_" + player.getUid()).getBytes());
        try {
            UserProto proto = UserProto.parseFrom(bytes);
            player.send(proto);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveUser(String name, Player player) {
        UserProto.Builder builder = UserProto.newBuilder();
        builder.setId(player.getUid());
        builder.setName(name);
        jedis.set(("u_" + player.getUid()).getBytes(), builder.build().toByteArray());
        NotifyCodeProto.Builder notifyCodeBuilder = NotifyCodeProto.newBuilder();
        notifyCodeBuilder.setCode(2);//2 success
        player.send(notifyCodeBuilder.build());
    }

}
